package org.example.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import jakarta.annotation.Resource;
import org.example.order.bean.Order;
import org.example.order.properties.OrderProperties;
import org.example.order.service.OrderService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.swing.text.html.HTMLDocument;
import java.math.BigDecimal;

/**
 * @Author : wer
 * @Date: 2025/6/21 16:06
 * @Description: 订单服务api
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderProperties orderProperties;

    @GetMapping("/config")
    public String config() {
        return "orderTimout:" + orderProperties.getTimout()
                + ";orderAutoConform:" + orderProperties.getAutoConform()
                + ";orderDbUrl:" + orderProperties.getDbUrl();
    }

    //创建订单
    @GetMapping("/create")
    public Order create(@RequestParam("userId") Long userId,
                        @RequestParam("productId") Long productId) {
        return orderService.createOrder(productId, userId);
    }

    // 流控模式-链路
    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallback")
    public Order seckill(@RequestParam("userId") Long userId,
                         @RequestParam("productId") Long productId) {
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    /**
     * @param userId    用户id
     * @param productId 商品id
     * @param e         异常
     * @return 秒杀异常兜底order
     * <p>
     * 需求1：每个用户秒杀QPS不得超过1（userId限制）
     * 需求2：设置vip用户不限制QPS
     * 需求3：设置一个下架商品不允许访问
     */
    public Order seckillFallback(Long userId, Long productId,
                                 Throwable e) {
        System.out.println("seckillFallback...");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息：" + e.getClass().getSimpleName());
        order.setNickName("未知用户");
        order.setTotalAmount(new BigDecimal(0));
        return order;
    }

    // 流控模式-关联-写
    @GetMapping("writeDb")
    public String writeDb() {
        return "writeDb success ...";
    }

    // 流控模式-关联-读
    @GetMapping("readDb")
    public String readDb() {
        return "readDb  success ...";
    }
}
